package com.ugrow.ugrowcommunity.activity.warranty;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.ugrow.ugrowcommunity.R;

import java.text.SimpleDateFormat;
import java.util.Date;

public class EditActivity extends AppCompatActivity {

    private NoteBean noteBean;
    private EditText etTitle, etContent;
    private MyOpenHelper myOpenHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit);

        etTitle = findViewById(R.id.et_title);
        etContent = findViewById(R.id.et_content);
        myOpenHelper = new MyOpenHelper(this);
        findViewById(R.id.back).setOnClickListener(v -> finish());
        initData();
    }

    private void initData() {
        Intent intent = getIntent();
        noteBean = (NoteBean) intent.getSerializableExtra("noteBean");
        if (noteBean != null) {
            etTitle.setText(noteBean.getTitle());
            etContent.setText(noteBean.getContent());
        }
    }

    public void save(View view) {
        String title = etTitle.getText().toString();
        String content = etContent.getText().toString();
        if (TextUtils.isEmpty(title)) {
            Toast.makeText(this, "请填写宿舍号", Toast.LENGTH_SHORT).show();
            return;
        }

        noteBean.setTitle(title);
        noteBean.setContent(content);
        noteBean.setCreatedTime(getCurrentTimeFormat());

        long rowId = myOpenHelper.updateData(noteBean);
        if (rowId != -1) {
            Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "修改失败", Toast.LENGTH_SHORT).show();
        }

    }

    @SuppressLint("SimpleDateFormat")
    private String getCurrentTimeFormat() {
        SimpleDateFormat simpleDateFormat = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            simpleDateFormat = new SimpleDateFormat("YYYY年MM月dd HH:mm:ss");
        }
        Date date = new Date();
        return simpleDateFormat != null ? simpleDateFormat.format(date) : "未知";
    }
}